package com.mojawa.mj_amap.manager

import com.amap.api.maps.model.LatLng
import com.mojawa.mj_amap.location.MJRunAmapUtil

class MJLocationDataManager() {
    private var points: MutableList<LatLng> = mutableListOf()  // 点的集合
    var totalDistance: Double = 0.00 // 距离
    var presentPoints: LatLng? = null

    /**
     * 添加点
     */
    fun addPoint(newPoints: List<LatLng>?) {
        if (newPoints.isNullOrEmpty()) return

        // 将新点添加到已有点的集合中
        val lastPoint = points.lastOrNull()
        for (newPoint in newPoints) {
            // 仅当新点与上一个点不同的时候，才添加
            if (lastPoint == null || newPoint != lastPoint) {
                points.add(newPoint)
                // 如果当前有至少两个点，计算距离
                if (points.size >= 2) {
                    val lastTwoPoints = points.takeLast(2)

                    val distance = calculateDistance(lastTwoPoints)
                    if (distance <= 30){
                        totalDistance += distance
                    }

                }
            }
        }
    }

    fun clearPoints() {
        points.clear()
    }

    fun saveLocationData(points: List<LatLng>, totalDistance: Double) {
        this.points.addAll(points)  // 将新的点添加到集合中，累积数据
        this.totalDistance += totalDistance
    }

    // 获取到所有点
    fun getPoints(): List<LatLng> {
        return points
    }

    /**
     * 获取到当前点
     */
    fun getPoint(): LatLng? {
        return presentPoints
    }

    private fun calculateDistance(newPoints: List<LatLng>): Float {
        // 计算距离的逻辑
        return MJRunAmapUtil.getDistance(newPoints)
    }
}
